import { isObject } from 'lodash-es'

import {
  BwCustomComPropDataTypeEnum,
  BwComPropSetConstValueComEnum,
  BwCustomComFrontTypeEnum as BwFrontTypeEnum,
  type BwCustomComStructModel,
  type BwCustomComPropInfoModel,
  type BwCustomComDesignInfoModel,
} from '@bitwit/base-com-render'

/**
 * 初始化自定义组件外发属性信息
 * @param props                     属性信息
 */
function initComProps(props?: Nullable<Array<BwCustomComPropInfoModel>>) {
  if (Array.isArray(props) && props.length) {
    return props
  } else {
    const newProps: Array<BwCustomComPropInfoModel> = [
      {
        key: 'isRead',
        name: '组件是否是阅读模型',
        isRequire: false,
        dataType: [BwCustomComPropDataTypeEnum.boolean],
        remark: '组件是否是阅读模型',
        constValueSetCom: BwComPropSetConstValueComEnum.switch,
        constValueSetComProps: null,
      },
    ]
    return newProps
  }
}

/**
 * 初始化自定义组件自定义逻辑
 * @param setup                     自定义逻辑
 */
function initSetup(setup?: Record<BwFrontTypeEnum, string>) {
  if (isObject(setup)) {
    return setup
  } else {
    // @ts-ignore
    const curSetup: Record<BwFrontTypeEnum, string> = {}
    const setupLogic = `export default {
  setup(props, emit, expose){
    const { ref } = bwUtils
    const curEle = ref()
    return { curEle }
  }
}`
    curSetup[BwFrontTypeEnum.pc] = setupLogic
    curSetup[BwFrontTypeEnum.ios] = setupLogic
    curSetup[BwFrontTypeEnum.android] = setupLogic
    return curSetup
  }
}

/**
 * 初始化自定义组件DOM树
 * @param structs                      DOM树
 */
function initDesignStructs(
  structs?: Record<BwFrontTypeEnum, Array<BwCustomComStructModel>>
) {
  if (isObject(structs)) {
    return structs
  } else {
    // @ts-ignore
    const structs: Record<BwFrontTypeEnum, Array<BwCustomComStructModel>> = {}
    structs[BwFrontTypeEnum.pc] = []
    structs[BwFrontTypeEnum.ios] = []
    structs[BwFrontTypeEnum.android] = []
    return structs
  }
}

/** 初始化自定义组件样式 */
function initDesignCss(css?: Record<BwFrontTypeEnum, string | null>) {
  if (isObject(css)) {
    return css
  } else {
    // @ts-ignore
    const css: Record<BwFrontTypeEnum, string | null> = {}
    css[BwFrontTypeEnum.pc] = null
    css[BwFrontTypeEnum.ios] = null
    css[BwFrontTypeEnum.android] = null
    return css
  }
}

/**
 * 初始化设计信息
 * @param info                      设计信息
 */
export function infoDesignInfo(info?: BwCustomComDesignInfoModel | null) {
  const curDesignInfo: BwCustomComDesignInfoModel = {
    emits: info?.emits ?? null,
    comSlots: info?.comSlots ?? null,
    version: info?.version ?? '1.0.0',
    designVersion: info?.designVersion ?? '1.0.0',
    comCode: info?.comCode ?? '',
    comName: info?.comName ?? '',
    comPropsSetConfig: info?.comPropsSetConfig ?? undefined,
    comCss: initDesignCss(info?.comCss),
    comProps: initComProps(info?.comProps),
    setup: initSetup(info?.setup),
    structs: initDesignStructs(info?.structs),
  }

  return curDesignInfo
}
